package com.lsw.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.widget.EditText;

/**
 * Created by lsw on 2017/11/24.
 * 输入银行卡，四位一空格
 */

@SuppressLint("AppCompatCustomView")
public class BankEditText extends EditText implements TextWatcher {
    public BankEditText(Context context) {
        super(context, null);
    }

    public BankEditText(Context context, AttributeSet attrs) {
        super(context, attrs, 0);
    }

    public BankEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    public void init() {
        addTextChangedListener(this);
    }

    int beforeTextLength = 0;
    int onTextLength = 0;

    @Override
    public void afterTextChanged(Editable s) {
        // TODO Auto-generated method stub  
        String str = this.getText().toString();
        onTextLength = str.length();
        if (onTextLength > beforeTextLength) {
            if (str.length() == 5 || str.length() == 10 || str.length() == 15 || str.length() == 20 || str.length() == 25) {
                this.setText(new StringBuffer(str).insert(
                        str.length() - 1, " ").toString());
                this.setSelection(this.getText()
                        .length());
            }
        } else {
            if (str.startsWith(" ")) {
                this.setText(new StringBuffer(str).delete(
                        onTextLength - 1, onTextLength).toString());
                this.setSelection(this.getText()
                        .length());
            }
        }
    }


    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
                                  int after) {
        // TODO Auto-generated method stub  
        beforeTextLength = s.length();

    }


    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        // TODO Auto-generated method stub  

    }
}
